package com.atguigu.spzx.manager.handler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.dto.product.CategoryExcelDTO;
import jakarta.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
//没有注入到容器中的类的实体 无法从容器中装配对象使用
public class CategoryExcelListener extends AnalysisEventListener<CategoryExcelDTO> {

    CategoryMapper categoryMapper;

    public CategoryExcelListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }
    private List<CategoryExcelDTO> list = new ArrayList<>();
    private int limit = 100;
    @Override
    public void invoke(CategoryExcelDTO data, AnalysisContext context) {
        //检查数据库中是否已存在本次读取到的数据
        // id已存在、 parent_id&name相同的
        Long count = categoryMapper.selectCountByCondition(data);
        if(count>0){
            return;
        }
        list.add(data);
        if(list.size()>=limit){
            //批量保存数据到数据库
            categoryMapper.saveBatch(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(list.size()>0){
            categoryMapper.saveBatch(list);
            list.clear();
        }
    }
}
